package com.lmx.persistence.service;

import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lmx.common.constants.ICommonConstants;
import com.lmx.repoDomain.tmodel.DeviceType;
import com.lmx.repoDomain.tmodel.Tenant;

@Service
@Scope("prototype")
public class DeviceTypeService {
	private Log logger = LogFactory.getLog(this.getClass());
	
    @Autowired
    private GenericService dslJpaService;
    @Autowired
	private TenantService<Tenant> tenantSrv;
    @Autowired
    private CommonService commonSrv;
	@PersistenceContext
	private EntityManager em;
    
	/**
	 * 获取租户未分配的设备类型列表
	 * @author ytche
	 * @param tenantId
	 * @return
	 * @date 2017年4月14日 下午5:26:46
	 */
	public List<DeviceType> findDeviceTypeList(Long tenantId){
		List<DeviceType> dataList=Lists.newArrayList();
		List<DeviceType> allList=this.findDeviceTypesByTenant(ICommonConstants.ADMIN_TENANT_ID);
		List<DeviceType> tenantList=this.findDeviceTypesByTenant(tenantId);
		Map<String, String> tenantMap=Maps.newHashMap();
		
		//已经分配给租户的设备类型删掉
		for (DeviceType deviceType : tenantList) {
			tenantMap.put(deviceType.getDeviceName(), deviceType.getDeviceName());
		}
		for (DeviceType deviceType : allList) {
			if (!tenantMap.containsKey(deviceType.getDeviceName())) {
				dataList.add(deviceType);
			}
		}
		return dataList;
	}
	/**
	 * 获取用户当前的设备类型列表
	 * @author ytche
	 * @param tenant
	 * @return
	 * @date 2017年4月5日 下午6:33:47
	 */
	public List<DeviceType> findDeviceTypesByTenant(Long tenantId) {
		Tenant tenant=this.tenantSrv.getTenantById(tenantId);
		String queryStr="select d from DeviceType d where tenant = ?1 and delStatus = 0";
		List<DeviceType> types=this.em.createQuery(queryStr).setParameter(1, tenant).getResultList();
		return types;
	}
}
